package edu.suda.scratcher.ippgserver.servlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.ibatis.session.SqlSession;
import edu.suda.scratcher.ippgserver.mapper.*;
import edu.suda.scratcher.ippgserver.beans.*;

@WebServlet("/login")
public class Login extends Action {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");       
        HttpSession session = request.getSession(true);
        Writer writer = response.getWriter();
        
        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");
        
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUser(username);
        
        if (user!=null && user.getPasswd().compareTo(passwd)==0) {
            session.setAttribute("username", username);
            writer.write("ok");
        } else {
            writer.write("denied");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    
}
